<template>
  <el-dialog
    v-model="dialogVisible"
    title="搜索消息"
    width="600px"
    :before-close="handleClose"
  >
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="输入关键词搜索消息..."
        :prefix-icon="Search"
        @input="handleSearch"
        @keyup.enter="handleSearch"
        clearable
        class="search-input"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch" :loading="searching" />
        </template>
      </el-input>
    </div>

    <div class="search-results">
      <el-empty v-if="searchResults.length === 0 && searchKeyword && !searching"
                description="没有找到相关消息"
                :image-size="80" />

      <div v-else-if="searchResults.length > 0" class="results-list">
        <el-card
          v-for="(result, index) in searchResults"
          :key="index"
          @click="handleResultClick(result)"
          class="result-item"
          shadow="hover"
        >
          <div class="result-header">
            <el-avatar :size="32" :src="getAvatarUrl(result.sender_icon)" />
            <div class="result-info">
              <el-text class="sender-name" tag="b">{{ result.sender_nickname }}</el-text>
              <el-text size="small" type="info">{{ formatTime(result.created_at) }}</el-text>
            </div>
          </div>
          <div class="result-content">
            <el-text v-html="highlightKeyword(result.content)"></el-text>
          </div>
          <div v-if="result.receiver_nickname" class="result-receiver">
            <el-text size="small" type="info">发送给: {{ result.receiver_nickname }}</el-text>
          </div>
        </el-card>
      </div>
    </div>

    <div v-if="searching" class="loading-container">
      <el-loading-service />
    </div>
  </el-dialog>
</template>

<script>
import http from '../utils/http'
import dayjs from 'dayjs'
import { Search } from '@element-plus/icons-vue'

export default {
  name: 'MessageSearch',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'message-selected'],
  data() {
    return {
      searchKeyword: '',
      searchResults: [],
      searching: false,
      Search
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      }
    }
  },
  methods: {
    async handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.searchResults = []
        return
      }

      this.searching = true
      
      try {
        const response = await http.get('/messages/search', {
          params: {
            keyword: this.searchKeyword.trim(),
            limit: 20
          }
        })

        if (response.data.success) {
          this.searchResults = response.data.messages
        } else {
          this.searchResults = []
        }
      } catch (error) {
        console.error('搜索消息失败:', error)
        this.searchResults = []
      } finally {
        this.searching = false
      }
    },

    highlightKeyword(content) {
      if (!this.searchKeyword) return content
      
      const keyword = this.searchKeyword.trim()
      const regex = new RegExp(`(${keyword})`, 'gi')
      return content.replace(regex, '<mark>$1</mark>')
    },

    formatTime(timestamp) {
      return dayjs(timestamp).format('MM-DD HH:mm')
    },

    handleClose() {
      this.dialogVisible = false
      this.clearSearch()
    },

    handleResultClick(result) {
      this.$emit('message-selected', result)
      this.dialogVisible = false
    },

    getAvatarUrl(icon) {
      return icon ? `/images/face/${icon}` : '/images/face/default.png'
    },

    clearSearch() {
      this.searchKeyword = ''
      this.searchResults = []
    }
  },
  watch: {
    dialogVisible(newVal) {
      if (!newVal) {
        // 关闭对话框时清空结果
        setTimeout(() => {
          this.clearSearch()
        }, 300)
      }
    }
  }
}
</script>

<style scoped>
.search-container {
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
}

.search-results {
  max-height: 400px;
  overflow-y: auto;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-item {
  cursor: pointer;
  transition: all 0.2s;
}

.result-item:hover {
  transform: translateY(-1px);
}

.result-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.result-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.sender-name {
  font-weight: 500;
}

.result-content {
  margin-bottom: 8px;
  line-height: 1.4;
}

.result-content :deep(mark) {
  background: var(--el-color-warning-light-7);
  padding: 1px 2px;
  border-radius: 2px;
  color: var(--el-color-warning-dark-2);
}

.result-receiver {
  text-align: right;
}

.loading-container {
  position: relative;
  height: 100px;
}
</style>
